//
//  FZCollectionViewController.swift
//  FZImageBrowser
//
//  Created by 李雷川 on 16/5/28.
//  Copyright © 2016年 李雷川. All rights reserved.
//Module 'SnapKit' was created for incompatible target arm64-apple-ios10.0: /Users/yinjining/Desktop/方正项目/封装库/FZSFImageBrowser/Carthage/Build/iOS/SnapKit.framework/Modules/SnapKit.swiftmodule/arm64.swiftmodule

import UIKit
import SDWebImage
import SnapKit

private let  kBrowseSpace:CGFloat = 32.0
private let reuseIdentifier = "BrowseCell"

public  protocol FZBrowseViewScrollDelegate:NSObjectProtocol
{
    //回调方法 传一个String类型的值
    func scrollToIndex(indexpath:IndexPath);
}

public  class FZBrowseViewController: UIViewController {
    
    // 退出大图浏览时的回调   index 为当前的位置
    public var closeImageBroswerEvent:((_ index: Int)->Void)?
    
    var screenWidth:CGFloat =  0.0
    var screenHeight:CGFloat = 0.0
    public var sourceView:UIView?
    public var pageChanged:((_ index:Int)->Void)?
    public var exit:((_ index:Int)->Void)?
    public var limiteMAXHeight :Bool = false;//是否限制高度
    public var delegate : FZBrowseViewScrollDelegate?
    public var browseItems = [FZBrowseModel]()
    public var holderImage :UIImage?
    public var whiteVlaue:CGFloat  = 0 //0:黑色；1：白色
    fileprivate let pageControl = UIPageControl()
    var titleInfoviewWidth:CGFloat=0.0
    // 初始的index 用于比对滑动后的index是否和初始值一致 一致则带动画 否则直接返回
    var originalIndex :Int?
    var infoTitleLab=CTView()
    public var longPressClouse:((_ image:UIImage)->Void)?
    public var currentIndex = 0{
        didSet
        {
            pageControl.currentPage = currentIndex
            self.updateTitleInfo()
        }
    }
    var collectionView:UICollectionView!
    deinit{
        NotificationCenter.default.removeObserver(self, name:UIDevice.orientationDidChangeNotification, object: nil)
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.init(white: whiteVlaue, alpha: 0);
        self.navigationController?.isNavigationBarHidden = true
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBar.isTranslucent = true
        NotificationCenter.default.addObserver(self, selector:#selector(FZBrowseViewController.deviceOrientationDidChange(_:)) , name:UIDevice.orientationDidChangeNotification , object: nil)
        buildUI()
        setUptitleInfoView()
        self.upShowDetalText()
        let longPressGesture = UILongPressGestureRecognizer(target: self, action:#selector(handleLongPress(_:)))
        self.view.addGestureRecognizer(longPressGesture)
 
    }
    
    override public var prefersStatusBarHidden : Bool {
        return true
    }
    override public var preferredStatusBarUpdateAnimation: UIStatusBarAnimation{
        return .none
    }
    
    
    @objc func deviceOrientationDidChange(_ note:Notification)  {
        layoutSubView()
    }
    
    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

 
    override public  func viewDidAppear(_ animated: Bool) {
        self.showImageBroswer()
    }
    
    func buildUI(){
        setupScreenSize()
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        layout.sectionInset =  UIEdgeInsets.zero
        layout.minimumInteritemSpacing = 0
        let width = screenWidth + kBrowseSpace
        layout.itemSize = CGSize.init(width: width, height: screenHeight)
        let collectionView = UICollectionView(frame:CGRect(x: 0, y: 0,width: width , height: screenHeight) , collectionViewLayout: layout)
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.isPagingEnabled = true
        collectionView.bounces = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.contentOffset = CGPoint(x: CGFloat(currentIndex) * width, y: 0)
        
        self.collectionView = collectionView
        view.addSubview(collectionView)
        collectionView.register(FZBrowseCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.isHidden = true
        collectionView.backgroundColor = UIColor.clear
        setupPageControl()
    }

    func setupScreenSize(){
        screenWidth = view.frame.width
        screenHeight = view.frame.height
    }
    
    
    func setupPageControl(){
        pageControl.numberOfPages = browseItems.count
        pageControl.hidesForSinglePage = true
        pageControl.currentPage = currentIndex
        pageControl.currentPageIndicatorTintColor = UIColor.init(red: 190/255, green: 190/255, blue: 190/255, alpha: 1)
        pageControl.pageIndicatorTintColor = UIColor.init(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
        view.addSubview(pageControl)
        pageControl.snp.makeConstraints { (make) in
            make.centerX.bottom.equalTo(view)
        }
    }
    
    
    func layoutSubView(){
        setupScreenSize()
        let width = screenWidth + kBrowseSpace
        collectionView.collectionViewLayout.invalidateLayout()
        collectionView.frame = CGRect(x: 0, y: 0,width: width , height: screenHeight)
        collectionView.contentOffset = CGPoint(x: CGFloat(currentIndex) * width, y: 0)
        collectionView.reloadData()
        pageControl.frame = CGRect(x: 0, y: screenHeight - 50, width: screenWidth, height: 50)
    }
    
    func updateTitleInfo(){
        let brosweModel = browseItems[currentIndex]
        self.navigationItem.title = brosweModel.info + "   (\(currentIndex+1)/\(browseItems.count))"
    }
    func upShowDetalText(){
        let brosweModel = browseItems[currentIndex]
        if brosweModel.textS?.count ?? 0 > 0 && brosweModel.showText.count > 1 {
                self.titleInfoBottomV.isHidden=false
                self.showDetlaText(text:brosweModel.showText)
            }else{
            self.titleInfoBottomV.isHidden=true
        }
    }
//    显示描述文字
    func showDetlaText(text:String){
        titleInfoviewWidth=getTexWidth(textStr: text , height: 300)
        titleInfoviewWidth=titleInfoviewWidth+70
        self.view.addSubview(titleInfoBottomV)
        titleInfoBottomV.snp.updateConstraints{ make in
            make.left.top.bottom.equalTo(0)
            make.width.equalTo(titleInfoviewWidth)
        }
        infoTitleLab.removeFromSuperview()
        let label = CTView()
        label.lineGap = CGFloat(5);
        label.knerGap = CGFloat(2);
        label.fontColor = UIColor.white
        label.fontSize = 18
        label.backgroundColor = UIColor.clear;
        label.verticalForm = true
        label.text=text
        infoTitleLab=label
        titleInfoBottomV.addSubview(infoTitleLab)

        infoTitleLab.snp.updateConstraints { (make) in
            make.left.equalToSuperview();
            make.right.equalTo(-40)
            make.height.equalTo(300)
            make.centerY.equalToSuperview()
        }

        self.isOpeninfoV()
    }
    func setUptitleInfoView(){
        self.view.addSubview(titleInfoBottomV)
        titleInfoBottomV.snp.makeConstraints { make in
            make.left.top.bottom.equalTo(0)
            make.width.equalTo(titleInfoviewWidth+70)
        }
        titleInfoBottomV.addSubview(arrowBtn)
        arrowBtn.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 20, height: 35))
        }
    }
   @objc func arrowBtnClick(sender:UIButton){
    sender.isSelected = !sender.isSelected
    self.isOpeninfoV()
   }
    func isOpeninfoV(){
        if  arrowBtn.isSelected==true{//关
           UIView.animate(withDuration: 0.3, animations: {
               
               self.titleInfoBottomV.snp.updateConstraints{ make in
                   make.left.equalTo(-self.titleInfoviewWidth+40)
                   make.top.bottom.equalTo(0)
                   make.width.equalTo(self.titleInfoviewWidth)
               }
           });
        }else{//开
           UIView.animate(withDuration: 0.3, animations: {
               self.titleInfoBottomV.snp.updateConstraints{ make in
                   make.top.left.bottom.equalTo(0)
                   make.width.equalTo(self.titleInfoviewWidth)
               }
           });
        }
    }
    lazy var titleInfoBottomV:UIView={
        let view=UIView.init()
        view.backgroundColor=UIColor.init(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.6)
        return view
    }()
    lazy var arrowBtn:UIButton={
        let btn=UIButton.init()
        btn.setImage(UIImage.init(named: "left_slider_appreciation"), for: .normal)
        btn.setImage(UIImage.init(named: "right_slider_appreciation"), for: .selected)
        btn.addTarget(self, action: #selector(arrowBtnClick(sender:)), for: .touchUpInside)
        return btn
    }()
    //创建竖着显示的label
//    lazy var infoTitleLab:CTView={
//        let label = CTView()
//        label.lineGap = CGFloat(5);
//        label.knerGap = CGFloat(2);
//        label.fontColor = UIColor.white
//        label.fontSize = 18
//        label.backgroundColor = UIColor.clear;
//        label.verticalForm = true
//        return label;
//    }()
//
    //计算文字宽度的方法
    func getTexWidth(textStr:String,height:CGFloat) -> CGFloat {
        
        let width = CTView.returnTextWidth(with: textStr, lineGap: CGFloat(5), knetGap: CGFloat(2), fonSize:18, maxHeight: height);
        
        return width;
    }
    public func updatePageIndex(index:Int){
        self.currentIndex = index
        let width = screenWidth + kBrowseSpace
        collectionView.contentOffset = CGPoint(x: CGFloat(currentIndex) * width, y: 0)
    }
    
    func showImageBroswer(){
        originalIndex = currentIndex
        if let sourceView = sourceView{
            let convertFrame = sourceView.convert(sourceView.bounds, to:  UIApplication.shared.keyWindow)
            let tempImageView = UIImageView(image:tempImage(index:currentIndex))
            tempImageView.frame = convertFrame
            tempImageView.contentMode = .scaleAspectFit
            tempImageView.backgroundColor  = UIColor.clear
            UIApplication.shared.keyWindow?.addSubview(tempImageView)
            UIView.animate(withDuration: 0.2, animations:{
                let windowRect = (UIApplication.shared.keyWindow?.bounds)!
                if self.limiteMAXHeight{
                    tempImageView.frame = CGRect.init(x:windowRect.origin.x, y: windowRect.origin.y + 64, width: windowRect.size.width, height: windowRect.size.height - 128)
                }else{
                    tempImageView.frame = windowRect;
                }
                self.view.backgroundColor = UIColor.init(white:self.whiteVlaue, alpha: 1);
            }, completion: {
                (finished) in
                tempImageView.removeFromSuperview()
                self.collectionView.isHidden = false
            })
        }else{
            self.collectionView.isHidden = false
            self.view.backgroundColor = UIColor.init(white:whiteVlaue, alpha: 1)
        }
    }
    
    
    func closeImageBroswer(){
        if let sourceView = sourceView{
            
            
            guard self.originalIndex == self.currentIndex else {
                
                self.dismiss(animated: false, completion: nil)
                self.exit?(self.currentIndex)
                return
            }
            
            
            let convertFrame = sourceView.convert(sourceView.bounds, to:  UIApplication.shared.keyWindow)
            var image = currentImage(index: currentIndex)
            if(image == nil){
                image = tempImage(index: currentIndex)
            }
            let tempImageView = UIImageView(image:image)
            tempImageView.backgroundColor  = UIColor.clear
            let windowRect = (UIApplication.shared.keyWindow?.bounds)!
            if self.limiteMAXHeight{
                tempImageView.frame = CGRect.init(x:windowRect.origin.x, y: windowRect.origin.y + 64, width: windowRect.size.width, height: windowRect.size.height - 128)
            }else{
                tempImageView.frame = windowRect;
            }
            tempImageView.frame = windowRect
            tempImageView.contentMode = .scaleAspectFit
            UIApplication.shared.keyWindow?.addSubview(tempImageView)
            self.dismiss(animated: false, completion: nil)
            UIView.animate(withDuration: 0.2, animations:{
                tempImageView.frame = convertFrame
                self.view.backgroundColor = UIColor.init(white:self.whiteVlaue, alpha: 0);
            }, completion: {
                [weak self](finished) in
                tempImageView.removeFromSuperview()
                self?.exit?(self!.currentIndex)
            })
        }else{
            self.dismiss(animated: false, completion: nil)
            self.exit?(self.currentIndex)
        }
    }
    
    func tempImage(index:Int)->UIImage?{
        let item  = self.browseItems[index]
        if item.cacheImage != nil{
            return item.cacheImage
        }
        return holderImage;
    }
    
    func currentImage(index:Int)->UIImage?{
        let item  = self.browseItems[index]
        if item.originalImg != nil{
            return item.originalImg
        }
        if item.imageData != nil{
            return UIImage.init(data: item.imageData!)
        }
        if item.imagePath.count > 0{
            if let image = UIImage.init(contentsOfFile: item.imagePath){
                return image
            }
        }
        if item.imageUrl.count > 0 {
            if let image =  SDImageCache.shared.imageFromCache(forKey: item.imageUrl){
                return image
            }
        }
        return nil
    }
    @objc func handleLongPress(_ getsture:UILongPressGestureRecognizer){
        if(getsture.state  == .ended){
            guard let doClouse = longPressClouse else{
                return
            }
            guard let image = currentImage(index: currentIndex) else{
                return
            }
            doClouse(image)
        }
    }

}

extension FZBrowseViewController:UICollectionViewDataSource{
    // MARK: UICollectionViewDataSource
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return browseItems.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FZBrowseCollectionViewCell
        cell.zoomScrollView.limiteMAXHeight = self.limiteMAXHeight
        cell.zoomScrollView.zoomScale = 1.0
        cell.zoomScrollView.frame = CGRect(x: 0, y: 0,width: screenWidth , height: screenHeight)
        cell.zoomScrollView.contentSize = CGSize(width: screenWidth, height: screenHeight)
        cell.resetProgressLayer()
        cell.zoomScrollView.tapClouse = {
            [weak self]in
            self?.closeImageBroswer()
            if self?.originalIndex == indexPath.row {
                
            } else{
                self?.dismiss(animated: false, completion: nil)
            }
        }
        let browse = browseItems[indexPath.row]
        cell.progressLayer.isHidden = true
        if let image = self.currentImage(index: indexPath.row){
            cell.zoomScrollView.setImage(image)
            return cell
        }
        //防止点击图片时的黑屏
        if let tempImage = tempImage(index: indexPath.row){
            cell.zoomScrollView.setImage(tempImage)
        }
        if browse.imageUrl.count > 0{
            loadCellImage(cell: cell, browse: browse, imageUrl: browse.imageUrl, placeholderImage: tempImage(index: indexPath.row), isExecuteProgressBloack: true, loadImageCompletedBlock: { [weak browse](image) in
                // 原图赋值
                browse?.originalImg = image
            })
            return cell;
        }
        return cell;

    }
    
    func resizeImageUrl(imageUrl:String, percentage:Int)->String{
        let params = "?x-oss-process=image/resize,p_\(percentage)"
        let resizeImageUrl =  imageUrl + params
        return resizeImageUrl
    }
    
    /// - Parameters:
    ///   - isExecuteProgressBloack: 是否执行  ProgressBloack里的方法 default true
    func loadCellImage(cell:FZBrowseCollectionViewCell, browse:FZBrowseModel, imageUrl:String, placeholderImage:UIImage?, isExecuteProgressBloack:Bool,  loadImageCompletedBlock: ((_ image:UIImage?)->Void)? = nil) {
        
        cell.zoomScrollView.imageView.sd_setImage(with: URL.init(string: browse.imageUrl), placeholderImage: placeholderImage, options: [.delayPlaceholder], progress: { [weak cell] (receivedSize, expectedSize, url) in
            
            if cell == nil{
                return;
            }
            if expectedSize == 0{
                return;
            }
            
            if !isExecuteProgressBloack{
                return;
            }
            
            var  progress = Float.init(receivedSize) / Float.init(expectedSize);
            progress = progress < 0.01 ? 0.01 : progress > 1 ? 1 : progress;
            if  Float.init(nan: Float.RawSignificand(progress), signaling: true) == 0.0{
                progress = 0.0
            }
            DispatchQueue.main.async {
                cell?.progressLayer.isHidden = false;
                cell?.progressLayer.strokeEnd = CGFloat(progress)
            }
            
            
        }) {
            [weak cell] (image, error, _, _) in
            if cell == nil{
                return;
            }
            DispatchQueue.main.async {
                cell?.progressLayer.isHidden = true
                if image != nil{
                    cell?.zoomScrollView.setImage(image!);
                    loadImageCompletedBlock?(image)
                }
                
            }
            
        }
        
        
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize{
        let width = screenWidth + kBrowseSpace
        return CGSize(width:width, height: screenHeight)
    }

}


extension FZBrowseViewController:UICollectionViewDelegate{
    
}
extension FZBrowseViewController:UIScrollViewDelegate{
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let width = screenWidth + kBrowseSpace
        currentIndex = Int(scrollView.contentOffset.x / width)
        guard let doClouse = pageChanged else{
            return
        }
        doClouse(currentIndex)
    }
    
    
    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let width = screenWidth + kBrowseSpace
        let  index = Int(scrollView.contentOffset.x / width)
        self.upShowDetalText()
        //调用代理方法
        if((delegate) != nil)
        {
            let indexpath = IndexPath.init(row: index, section: 0);
            delegate?.scrollToIndex(indexpath: indexpath);
        }
    }
    
    public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        let width = screenWidth + kBrowseSpace
        
        let  index = Int(scrollView.contentOffset.x / width)
        //调用代理方法
        if((delegate) != nil)
        {
            let indexpath = IndexPath.init(row: index, section: 0);
            delegate?.scrollToIndex(indexpath: indexpath);
        }
        
    }
    
}

